<template>
    <div>
    <!-- 面包屑导肮区域 -->
    <el-breadcrumb      separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
        <el-row :gutter="20">
            <el-col :span="8">
                <el-input placeholder="请输入内容" v-model="queryInfo.query"
                clearable @clear="getGoodsList" >
                <el-button slot="append" icon="el-icon-search"
                @click="getGoodsList"></el-button>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="goAddpage">添加商品</el-button>
            </el-col>
        </el-row>
        <el-table :data="goodsList" border stripe="">
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="商品名称" prop="goods_name"></el-table-column>
            <el-table-column label="商品价格(元)" prop="goods_price" width="180px"></el-table-column>
            <el-table-column label="商品重量" prop="goods_weight" width="180px"></el-table-column>
            <el-table-column label="创建时间" prop="add_time" width="180px">
                <template slot-scope="scope">
                    {{scope.row.add_time | dateFormat}}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180px">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDiolog(scope.row.goods_id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete"
                    size="mini" @click="removeById(scope.row.goods_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
        ></el-pagination>
    </el-card>
    <!-- 编辑商品的对话框 -->
    <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
        <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="editForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="editForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="editForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="editForm.goods_weight"></el-input>
        </el-form-item>
        <!-- <el-form-item label="商品状态" prop="goods_state">
            <el-radio-group v-model="editForm.goods_state">
                <el-radio :label="0" v-if="editForm.goods_state == 0">未通过</el-radio>
                <el-radio :label="1" v-else-if="editForm.goods_state == 1">审核中</el-radio>
                <el-radio :label="2" v-else>已审核</el-radio>
            </el-radio-group>
        </el-form-item> -->
        <el-form-item label="是否热销" prop="is_promote">
            <el-switch
                v-model="editForm.is_promote"
                active-color="#13ce66"
                inactive-color="#ff4949">
            </el-switch>
        </el-form-item>
        <el-form-item label="热销数量" prop="hot_mumber">
            <el-input v-model="editForm.hot_mumber"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="pics">
            <el-upload
                :action="uploadURL"
                list-type="picture-card"
                :file-list="editForm.pics"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="headerObj"
                :on-success="handleSuccess">
                <i class="el-icon-plus"></i>
            </el-upload>
        </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog :visible.sync="previewVisible">
        <img width="100%" :src="previewPath" alt="">
    </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            // 商品查询对象
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:10
            },
            //总数据条数
            total:0,
            // 商品列表
            goodsList:[],
            editDialogVisible:false,
            editFormRules:{},
            editForm:{
                goods_name:'',
                goods_price:0,
                goods_number:0,
                goods_weight:0,
                goods_state:0,
                add_time:'',
                upd_time:'',
                hot_mumber:0,
                is_promote:'',
                pics:[]
            },
            //上传图片的URL地址
            uploadURL:'http://127.0.0.1:8888/api/private/v1/upload',
            headerObj:{
                Authorization:window.sessionStorage.getItem('token')
            },
            previewPath:'',
            previewVisible:false,
            //商品id
            goodsId:''
        }
    },
    created() {
        this.getGoodsList()
    },
    methods: {
        //根据分页获取对应的商品列表
        async getGoodsList(){
            const {data:res} = await this.$http.get('goods',{ params:this.queryInfo })

            if(res.meta.status !== 200){
            return this.$message.error('获取商品列表失败')
            }
            this.$message.success('获取商品列表成功')
            this.goodsList = res.data.goods
            this.total = res.data.total

        },
        //监听pagesize改变的时间
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize;
            this.getGoodsList();
            console.log(newSize);
        },
        //监听页码值改变的时间
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.getGoodsList();
            console.log(newPage);
        },
        // 编辑商品
        async showEditDiolog(id){
            this.goodsId = id
            const {data:res} = await this.$http.get(`goods/${id}`)
            if(res.meta.status !== 200){
                return this.$message.error('获取商品属性失败')
            }
            console.log(res);
            res.data.pics.forEach(item => {
                item.url = item.pics_sma_url
            });
            console.log(res)
            this.editForm = res.data
            this.editDialogVisible = true
        },
        //监听编辑商品的对话框关闭事件
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
            this.editForm.pics = [] 
        },
        //编辑商品确定按钮
        async editUserInfo(){
            const {data:res} = await this.$http.put(`goods/${this.goodsId}`,this.editForm)
            if(res.meta.status !== 200){
                return this.$message.error('商品信息更新失败')
            }
            this.$message.success('商品信息更新成功')
            this.editDialogVisible = false
            this.editForm.pics = []
        },
        //删除商品的事件
        removeById(id){
            this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
            .then(async ()=> {
                //删除的逻辑接口
                console.log(id)
                const {data:res} = await this.$http.delete(`goods/${id}`)
                if(res.meta.status !== 200){
                this.$message.error('删除参数失败，请重新删除')
            }

            this.$message({
                type: "success",
                message: "删除成功!"
            });
            this.getGoodsList()
            })
            .catch(() => {
                this.$message({
                type: "info",
                message: "已取消删除"
                });
            });
        },
        goAddpage(){
            this.$router.push('/goods/add')
        },
        //处理图片预览
        handlePreview(file){
            this.previewPath = file.url;
            this.previewVisible = true
        },
        //处理移除图片的操作
        handleRemove(file){
            //获取将要删除的图片的临时路径
            console.log(file)
            const filePath = file.url
            // 从pics数组中，找到这个图片对应的索引值
            const i = this.editForm.pics.findIndex(item => item.url == filePath)
            console.log(i)
            // 调用数组的splice方法。把图片信息对象从pics数组中移除
            this.editForm.pics.splice(i,1)
            console.log(this.editForm)
        },
        //监听图片上传成功的事件
        handleSuccess(response){
            //1.拼接得到的一个图片信息对象
            console.log(response)
            const picInfo = { pic:response.data.tmp_path ,url:response.data.url}
            //2.将图片信息对象push到PICS数组中
            this.editForm.pics.push(picInfo)
            console.log(this.editForm)
        },
    }
}
</script>
<style lang="less" scoped>
.goodsImg{
    width: 100% !important
}
</style>